
#! /usr/bin/python

import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        self.setDefaultBehaviour(self.MainBehav())

    class MainBehav(Behaviour.OneShotBehaviour):


        def _process(self):
            print "Agent "+agent+" registering"
            o=MyOrganization(b,nick="gestor",name="turismo", goalList={"ofrece":["informacion sobre resturantes","reservas a resturantes"],"necesita":["fuentes de informacion","fuentes de reservas"]})
            self.myAgent.createOrganization(o)
            mens=Behaviour.ACLTemplate()
            mens.setPerformative("request")
            mens.setOntology("Restaurant:Informacion")
            temp = Behaviour.MessageTemplate(mens)
            self.setTemplate(temp)
            ans=None
            ans=self._receive(True,10)
            while not ans or not temp.match(ans):
                 ans=self._receive(True,10)
            info=o.askMembers(ans.getContent())
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("inform")
            mens.setOntology("Restaurant:Informacion")
            mens.setSender(self.myAgent.getAID())
            mens.addReceiver(ans.getSender())
            mens.setContent(str(info))
            mens.setConversationId(ans.getConversationId())
            self.myAgent.send(mens)
            mens=Behaviour.ACLTemplate()
            mens.setPerformative("request")
            mens.setOntology("Restaurant:Reserva")
            temp = Behaviour.MessageTemplate(mens)
            self.setTemplate(temp)
            ans=None
            ans=self._receive(True,10)
            while not ans or not temp.match(ans):
                 ans=self._receive(True,10)
            print ans
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("request")
            mens.addReceiver(self.myAgent.getAID())
            mens.setOntology("Restaurant:Reserva")
            mens.setContent(ans.getContent())
            o.team.sendMessage(mens)
            print "Buscando mensaje"
            a=None
            a=o.team.receiveMessage()
            while not a or o.team.nick in str(a.getSender().getName()):
                 a=o.team.receiveMessage()
            print a
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("inform")
            mens.setOntology("Restaurant:reserva")
            mens.setSender(self.myAgent.getAID())
            mens.addReceiver(ans.getSender())
            mens.setContent(str(a.getContent()))
            mens.setConversationId(ans.getConversationId())
            print mens
            self.myAgent.send(mens)







class MyOrganization(Matrix.Matrix):
    def _process(self):
    	u=MyUnit(agent=self.myAgent, nick="gestor", name="informacion",password="pass",agentList=["sitea@apolo.dsic.upv.es"])
        self.addUnit(u)
        self.unit=u
        u=MyUnit2(agent=self.myAgent, nick="gestor",name="eoe",password="pass")
        self.team=u
        self.joinSupervisorTeam(u)
        time.sleep(2000)
        self.destroy()

    def askMembers(self,about):
        members=self.unit.getMemberList()
        print members
        mens=ACLMessage.ACLMessage()
        mens.setPerformative("request")
        mens.setSender(b.getAID())
        mens.setOntology("Restaurant:Informacion")
        mens.setContent(about)
        mens.setConversationId("id")
        self.unit.sendMessage(mens)
        time.sleep(30)
        ans=self.unit.receiveMessage()
        list=[]
        print "ANS",ans
        while ans:
            print ans
            if ans.getPerformative()=="inform":
                d={"info":str(ans.getContent())}
                list=list+[d]
            ans=self.unit.receiveMessage()
        return list
    def supervisionTest(self,sender,desc=None):
      result=0
      for i in desc:
          d=eval(str(i))
          if str(d["name"])=="ofrece" and str(d["value"])=="reservas a resturantes":
              result=result+1
          if str(d["name"])=="rol" and str(d["value"])=="supervision":
              result=result+1
      if result==2:
          return True
      return False

class MyUnit(Unit.Hierarchy):
    def _process(self):
        self.setGoal({"necesita":"fuentes de informacion"})
        self.addDataFormItem(name="ofrece",desc="lista de servicios que ofrece el agente")
        time.sleep(300)

    def entryUnitTest(self,sender,desc=None):
      for i in desc:
          d=eval(str(i))
          if str(d["name"])=="ofrece" and "fuentes de informacion" in str(d["value"]):
               return True
      return False


class MyUnit2(Unit.Team):
    def _process(self):
        #self.setGoal({"necesita":"fuentes de informacion"})
        time.sleep(300)


if __name__ == "__main__":
    agent = "brokerinformacion@apolo.dsic.upv.es"

    b = Example(agent,"pasword")
    b.start()





